﻿using BCEntity.OA.TeamWorks.TaskRecord;
using BCEntity.OA.TeamWorks.TaskRejectRecord;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using BCCommon;
namespace BCData.OA.TeamWorks.TaskRejectRecord
{
    public class TaskRejectRecordData : ITaskRejectRecordData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY = @"SELECT TaskRejectRecordId,TaskRecordNo,RejectRemark,RejectAdminId,RejectAdminFullName,RejectReceiverAdminId,
                                            RejectReceiverAdminFullName,CreateTime,WorkflowActivityInstanceId 
                                        FROM OA_TaskRejectRecord";

        public TaskRejectRecordData(IDatabaseContext databaseContext)
        {
            this.databaseContext=databaseContext;
        }

        /// <summary>
        /// 根据活动实例Id获取任务驳回记录
        /// </summary>
        /// <param name="workflowActivityInstanceId">活动实例Id</param>
        /// <param name="taskRecordNo">任务记录编号</param>
        /// <returns></returns>
        public async Task<TaskRejectRecordEntity> GetByWorkflowActivityInstanceId(long workflowActivityInstanceId, string taskRecordNo)
        {
            string sql = string.Format("{0} WHERE WorkflowActivityInstanceId=?WorkflowActivityInstanceId  AND TaskRecordNo=?TaskRecordNo", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowActivityInstanceId", workflowActivityInstanceId, DbType.Int64, size: 20);
            parameters.Add("?TaskRecordNo", taskRecordNo, DbType.AnsiString, size: 50);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<TaskRejectRecordEntity>(sql, parameters);
        }

        public async Task<TaskRejectRecordEntity> Add(TaskRejectRecordEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("OA_TaskRejectRecord", new string[] { "TaskRecordNo", "RejectRemark", "RejectAdminId", "RejectAdminFullName", "RejectReceiverAdminId",
                            "RejectReceiverAdminFullName", "WorkflowActivityInstanceId"});
            sql = string.Format("{0} {1} WHERE WorkflowActivityInstanceId=?WorkflowActivityInstanceId  AND TaskRecordNo=?TaskRecordNo", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowActivityInstanceId", entity.WorkflowActivityInstanceId, DbType.Int64, size: 20);
            parameters.Add("?TaskRecordNo", entity.TaskRecordNo, DbType.AnsiString, size: 50);
            parameters.Add("?RejectRemark", entity.RejectRemark, DbType.String);
            parameters.Add("?RejectAdminId", entity.RejectAdminId, DbType.Int64, size: 20);
            parameters.Add("?RejectAdminFullName", entity.RejectAdminFullName, DbType.AnsiString, size: 20);
            parameters.Add("?RejectReceiverAdminId", entity.RejectReceiverAdminId, DbType.Int64, size: 20);
            parameters.Add("?RejectReceiverAdminFullName", entity.RejectReceiverAdminFullName, DbType.AnsiString, size: 20);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<TaskRejectRecordEntity>(sql, parameters, databaseContext.Transaction);
        }

        public async Task<IEnumerable<TaskRejectRecordEntity>> GetByWorkflowActivityInstanceId(long workflowActivityInstanceId, long? adminId)
        {
            string sql = string.Format("{0} WHERE WorkflowActivityInstanceId=?WorkflowActivityInstanceId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowActivityInstanceId", workflowActivityInstanceId, DbType.Int64, size: 20);
            if (adminId.HasValue)
            {
                sql = string.Format("{0} AND (RejectReceiverAdminId=?AdminId OR RejectAdminId=?AdminId)", sql);
                parameters.Add("?AdminId", adminId, DbType.Int64, size: 20);
            }
            return await this.databaseContext.Master.QueryAsync<TaskRejectRecordEntity>(sql, parameters, databaseContext.Transaction);
        }

        public async Task<bool> CheckExists(long workflowActivityInstanceId, long taskRejectRecordId)
        {
            string sql = @"SELECT 1 FROM OA_TaskRejectRecord WHERE WorkflowActivityInstanceId=?WorkflowActivityInstanceId AND TaskRejectRecordId=?TaskRejectRecordId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowActivityInstanceId", workflowActivityInstanceId, DbType.Int64, size: 20);
            parameters.Add("?TaskRejectRecordId", taskRejectRecordId, DbType.Int64, size: 20);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        /// <summary>
        /// 根据活动实例Id获取任务驳回记录
        /// </summary>
        /// <param name="workflowActivityInstanceId">活动实例Id</param>
        /// <returns></returns>
        public async Task<IEnumerable<TaskRejectRecordEntity>> GetListByWorkflowActivityInstanceId(long workflowActivityInstanceId)
        {
            string sql = string.Format("{0} WHERE WorkflowActivityInstanceId=?WorkflowActivityInstanceId ", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowActivityInstanceId", workflowActivityInstanceId, DbType.Int64, size: 20);
            return await this.databaseContext.Slave.QueryAsync<TaskRejectRecordEntity>(sql, parameters);
        }

        /// <summary>
        /// 根据活动实例Id获取任务驳回记录列表
        /// </summary>
        /// <param name="workflowActivityInstanceId">活动实例Id</param>
        /// <param name="taskRecordNo">任务记录编号</param>
        /// <returns></returns>
        public async Task<IEnumerable<TaskRejectRecordEntity>> GetListByWorkflowActivityInstanceId(long workflowActivityInstanceId, string taskRecordNo)
        {
            string sql = string.Format("{0} WHERE WorkflowActivityInstanceId=?WorkflowActivityInstanceId  AND TaskRecordNo=?TaskRecordNo", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowActivityInstanceId", workflowActivityInstanceId, DbType.Int64, size: 20);
            parameters.Add("?TaskRecordNo", taskRecordNo, DbType.AnsiString, size: 50);
            return await this.databaseContext.Slave.QueryAsync<TaskRejectRecordEntity>(sql, parameters);
        }

        /// <summary>
        /// 分页获取驳回记录
        /// </summary>
        /// <param name="executerAdminId"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="sortName"></param>
        /// <param name="ascending"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<(IEnumerable<TaskRejectRecordViewEntity>, int)> GetListRejectRecordsAsync(long? executerAdminId, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize,int companyId)
        {
            string join_sql = @"SELECT B.TaskRecordNo,B.BusinessTypeName,B.BusinessType,B.WorkflowActivityInstanceId,B.TaskCategory,B.PauseTime,B.PauseRemark,B.RelevantTaskRecordNo,B.CurrentlyStep,B.TaskExecuterAdminId,
                                B.TaskExecuterFullName,B.StartTime,B.CompleteTime,B.TaskRemark,A.TaskRejectRecordId,A.RejectRemark,A.RejectAdminId,A.RejectAdminFullName,A.RejectReceiverAdminId,
                                A.RejectReceiverAdminFullName,A.CreateTime,CASE B.HandleStatus  WHEN  'Dismissed' THEN 'Rejected'
                                ELSE 'Rejected' END as HandleStatus
                                FROM  OA_TaskRejectRecord A
                                INNER  JOIN OA_TaskRecord B ON A.TaskRecordNo=B.TaskRecordNo";

            string join_sql_count = @"SELECT COUNT(1) FROM  OA_TaskRejectRecord A
                                INNER  JOIN OA_TaskRecord B ON A.TaskRecordNo=B.TaskRecordNo";

            List<string> wheres = new List<string>
            {
                "B.CompanyId =?CompanyId"
            };
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("CompanyId", companyId, DbType.Int32, size: 20);

            if (start.HasValue)
            {
                wheres.Add(" A.CreateTime>=?StartTime");
                parameters.Add("?StartTime", start.Value, DbType.DateTime);
            }
            if (end.HasValue)
            {
                wheres.Add(" A.CreateTime<=?EndTime");
                parameters.Add("?EndTime", end.Value, DbType.DateTime);
            }
            if (executerAdminId.HasValue)
            {
                wheres.Add(" B.TaskExecuterAdminId=?TaskExecuterAdminId");
                parameters.Add("?TaskExecuterAdminId", executerAdminId.Value, DbType.Int64, size: 20);
            }

            string sql = string.Format(@"{0} {1} ORDER BY {2} {3} LIMIT {4},{5}; 
                    {6} {1}",
                    join_sql,
                    wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                    !string.IsNullOrWhiteSpace(sortName) ? sortName : "A.CreateTime",
                    ascending.HasValue ? "ASC" : "DESC",
                    (pageIndex - 1) * pageSize,
                    pageSize,
                    join_sql_count);
            return await this.databaseContext.Slave.QueryPageableListAsync<TaskRejectRecordViewEntity>(sql, parameters);
        }
    }
}
